<?php
namespace app\admin\controller;
use app\admin\controller\base\BaseController;
use jayfun\mysqlTool\Backup;
use PHPMailer\PHPMailer\PHPMailer;
use think\Config;
use think\Request;

/**
 * 数据库控制器
 * Class DatabaseController
 * @package app\admin\controller
 */
class DatabaseController extends BaseController {
	/**
	 * 列表页
	 * @param Request $request
	 * @return mixed
	 */
	public function index(Request $request){
		$path = getcwd().DS.'data';
		$iterator = new \DirectoryIterator($path);
		$list = [];
		foreach ($iterator as $file){
			if ($file->getFilename() === '.' || $file->getFilename() === '..') continue;
			$list[] = [
				'name'=>$file->getFilename(),
				'create_time'=>$file->getCTime(),
				'size'=>$file->getSize(),
			];
		}
		$this->assign('list',$list);
		return $this->fetch();
	}

	/**
	 * 备份
	 * @param Request $request
	 */
	public function backup(Request $request){
		$config = Config::get('database');
		$database = [
			'username' => $config['username'],
			'password' => $config['password'],
			'host' => $config['hostname'].":".$config['hostport'],
			'database' => $config['database'],
		];
		$back_tool = new Backup($database);
		$filepath = $back_tool
			->setWithData(true)
			->setOutputPath('data'.DS)
			->dump();
		if($filepath !== false){
			$this->success('备份成功！');
		}else{
			$this->error('备份失败！');
		}
	}

	/**
	 * 删除备份文件
	 * @param Request $request
	 */
	public function delete(Request $request) {
		$name = $request->param('path');
		unlink('data'.DS.$name);
		$this->success('删除成功！');
	}

	/**
	 * 下载
	 * @param Request $request
	 */
	public function download(Request $request) {
		$name = $request->param('path');
		$file = new \SplFileObject('data'.DS.$name);
		header('Content-disposition: attachment; filename="' . $name . '"');
		header('Content-type: application/octet-stream');
		header("Accept-Ranges: bytes");
		header("Content-Length:".$file->getSize());
		while (!$file->eof()) {
			echo $file->fgets();
		}
	}

	/**
	 * 发送到邮箱
	 * @param Request $request
	 */
	public function email(Request $request) {
		$name = $request->param('path');
		$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
		try {
			//Server settings
			$mail->SMTPDebug = 0;                                 // Enable verbose debug output
			$mail->isSMTP();                                      // Set mailer to use SMTP
			$mail->Host = 'smtp.qq.com';  // Specify main and backup SMTP servers
			$mail->SMTPAuth = true;                               // Enable SMTP authentication
			$mail->Username = '000000000@qq.com';                 // SMTP username
			$mail->Password = '000000000000';                           // SMTP password
			$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
			$mail->Port = 25;                                    // TCP port to connect to

			//Recipients
			$mail->setFrom('000000000@qq.com', 'mao02');
			$mail->addAddress('0000000000@qq.com', 'jay');     // Add a recipient

			//Attachments
			$mail->addAttachment('data'.DS.$name);         // Add attachments

			//Content
			$mail->isHTML(true);                                  // Set email format to HTML
			$mail->Subject = 'mao02 数据库备份';
			$body = '';
			for ($i = 1; $i <= 100; $i++) {
				$body.=chr(rand(97, 122));
			}
			$mail->Body = $body;

			$mail->send();

			$this->success('邮件发送成功！');
		} catch (Exception $e) {
			$this->error($mail->ErrorInfo);
		}

	}

}